package com.learn.twoday;

import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

/**
 * 两阶段终止模式
 *
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/9
 */
public class TwoPhaseTermination {
    private static final Logger logger = Logger.getLogger(TwoPhaseTermination.class);

    public static void main(String[] args) {
        TwoPhase twoPhase = new TwoPhase();
        twoPhase.start();

        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        twoPhase.stop();
    }
}

class TwoPhase {
    private static final Logger logger = Logger.getLogger(TwoPhase.class);

    //        监控线程
    private Thread monitor;

    //        启动监控线程
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                if (thread.isInterrupted()) {
                    logger.debug("料理后事...");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);//情况1
                    logger.debug("执行监控记录");//情况2
                } catch (InterruptedException e) {
                    e.printStackTrace();
//                        因为sleep出现异常后，会清除打断标记
//                        重新设置打断标记
                    thread.interrupt();
                }
            }
        });

        monitor.start();
    }

    //        停止监控线程
    public void stop() {
        monitor.interrupt();
    }


}
